import json

import requests
from fastapi import APIRouter
from fastapi import HTTPException

from app.utils import UrlRequest, create_session


def send_post_request(session, url, headers, data):
    """发送 POST 请求"""
    try:
        response = session.post(url, headers=headers, data=data)
        response.raise_for_status()
        return response.text
    except requests.exceptions.RequestException as e:
        print(f"请求失败: {e}")
        return None


def extract_converted_url(response_data):
    """解析返回的 JSON，提取转换后的 URL"""
    try:
        response_json = json.loads(response_data)
        if response_json and isinstance(response_json, list):
            return response_json[0].get("converted", "")
    except json.JSONDecodeError:
        print("响应数据格式错误")
    return None


def convert_taobao_url(original_url):
    """转换淘宝链接"""
    session = create_session()
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.6533.100 Safari/537.36',
        'Referer': 'https://qqkq.xyz/',
        'Origin': 'https://qqkq.xyz',
        'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundary7RAHnjKVRi0wtRO0',
        'Accept': '*/*',
        'Accept-Language': 'zh-CN',
        'Sec-Fetch-Site': 'same-origin',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Dest': 'empty'
    }
    post_url = 'https://qqkq.xyz/convert.php'
    data = f"""------WebKitFormBoundary7RAHnjKVRi0wtRO0\r\nContent-Disposition: form-data; name=\"links\"\r\n\r\n[\"{original_url}\"]\r\n------WebKitFormBoundary7RAHnjKVRi0wtRO0--"""

    response_data = send_post_request(session, post_url, headers, data)

    if response_data:
        return extract_converted_url(response_data)
    return None


taobao = APIRouter(prefix="/dpapi/v1/taobao")


@taobao.post('/')
async def api_convert_taobao(request: UrlRequest):
    """淘宝链接解析 API"""
    converted_url = convert_taobao_url(request.url)
    if converted_url:
        return {"success": True, "data": converted_url}
    raise HTTPException(status_code=400, detail="未找到转换后的链接")
